package cn.atguigu.likedlist;

/**
 * 双向链表
 */
public class DoubleLikedListDome {
    public static void main(String[] args) {
        DoubleLikedListDome list = new DoubleLikedListDome();
        Hero2Node heroNode1 = new Hero2Node(1, "宋江", "及时雨");
        Hero2Node heroNode2 = new Hero2Node(2,"卢俊义","玉麒麟");
        Hero2Node heroNode3 = new Hero2Node(3,"吴用","智多星");
        Hero2Node heroNode4 = new Hero2Node(4,"入云龙","公孙胜");
        list.addByOrder(heroNode1);
        list.addByOrder(heroNode3);
        list.addByOrder(heroNode2);
        list.addByOrder(heroNode4);
        list.showList();
    }

    private Hero2Node head;

    public DoubleLikedListDome() {
        head = new Hero2Node(0, "", "");
    }

    public void addByOrder(Hero2Node newNode){
        Hero2Node temp = head;
        boolean flag = false;//序号相同标记

        while (true) {
            if (temp.next == null) {
                break;
            }
            //用下一个节点比较大小
            if (temp.next.no > newNode.no) {
                break;
            } else if (temp.next.no == newNode.no) {
                flag = true;
                break;
            }
            temp = temp.next;
        }

        if(flag){
            System.out.println("这个节点已经存在");
        }else {
            //需要找到当前节点的下一个节点的头部，依赖于当前节点的下一个节点的指针
            if(temp.next != null){
                temp.next.pro = newNode;
            }
            //pro
            newNode.pro = temp;

            //插入next到当前节点的下一个
            newNode.next = temp.next;
            temp.next = newNode;

        }

    }


    //显示链表数据
    public void showList(){
        if(head.next == null){
            System.out.println("此链表为空");
            return;
        }
        Hero2Node temp = head.next;
        do{
            System.out.println(temp);
            temp = temp.next;
            if(temp == null){
                break;
            }
        }while (true);
    }

}

class Hero2Node{
    public int no;
    public String name;
    public String nickName;
    /**
     * 下一个节点
     */
    public Hero2Node next;
    /**
     * 上一个节点
     */
    public Hero2Node pro;

    public Hero2Node(int no, String name, String nickName) {
        this.no = no;
        this.name = name;
        this.nickName = nickName;
    }

    @Override
    public String toString() {
        return "Hero2Node:{" +
                "no:" + no +
                ", name:'" + name + '\'' +
                ", nickName:'" + nickName + '\'' +
                ", next:" + next +
//                ", pro:" + pro +
                '}';
    }
}